const express = require('express')
const router = express.Router();
let multiparty = require("multiparty")
let fs = require("fs")
// let path = require("path")
const { qywxsend } = require('../serverOpt');

// 上传文件并更新version文件版本信息
router.post('/upFile', function (req, res) {
    // console.log(req.headers);
    // console.log(req.body);
    let form = new multiparty.Form();
    // 设置文件存储路径，以当前编辑的文件为相对路径
    // form.uploadDir = publicPath + "/static";
    // if (!fs.existsSync(publicPath + "/static")) {
    //     fs.mkdirSync(publicPath + "/static");
    // }
    // form.uploadDir = path.join(publicPath, 'static');
    form.uploadDir = "./opt/static/"
    // 检查并创建 public/static 目录
    if (!fs.existsSync(form.uploadDir)) {
        // console.log('Creating opt/static directory...');
        fs.mkdirSync(form.uploadDir, { recursive: true });
    }


    // 设置文件大小限制
    form.maxFilesSize = 2000 * 1024 * 1024;

    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log("upFile错误:", err);
            return res.json({
                msg: `错误:${err.message}`//
            })
        }
        // console.log("fields", fields);
        // console.log("files", files);
        try {
            // let keyStr = fields.files_up["0"];
            // if (keyStr && keyStr == "jb.3p?cnmf~a4d+dw9.3d?dfe456852f") {
                let inputFile = files.file[0];
                let newPath = form.uploadDir + "/" + inputFile.originalFilename;
                fs.renameSync(inputFile.path, newPath);
                let oldVarsion = 0
                try {
                    oldVarsion = fs.readFileSync(form.uploadDir + 'version.txt', 'utf-8')
                } catch (error) {
                    oldVarsion = 0
                }
                fs.writeFileSync(form.uploadDir + "version.txt", (Number(oldVarsion) + 1) + "")
                // qywxsend(`pdd脚本更新:版本号${(Number(oldVarsion) + 1)}`)
                res.json({
                    msg: "成功,版本" + (Number(oldVarsion) + 1)
                })
            // } else {
            //     res.json({
            //         msg: "失败,缺少必要参数"//jb.3p?cnmf~a4d+dw9.3d?dfe456852f
            //     })
            // }
        } catch (error) {
            res.json({
                msg: `错误:${error.message}`//
            })
        }
    });
})

module.exports = router;